/*** 本文件由CSMIS2.0-ModelCreater(UTF-8)工具辅助生成，版本1.0 ***/

package com.ce.sys.menu.action;

import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import com.ce.framework.constants.WebConstants;
import com.ce.framework.datamaintain.action.DataMaintainAction;
import com.ce.framework.datamaintain.logic.ISQLMapper;
import com.ce.framework.datamaintain.logic.ISearchCondition;
import com.ce.framework.exception.AppException;
import com.ce.framework.util.BeanAccessUtil;
import com.ce.framework.util.GeneratorUUID;
import com.ce.framework.util.LogUtil;
import com.ce.framework.util.StringUtil;
import com.ce.framework.util.node.JsonTreeNode;
import com.ce.sys.login.model.User;
import com.ce.sys.menu.dao.po.SysMenu;
import com.ce.sys.menu.dao.po.SysMenuOperations;
import com.ce.sys.menu.logic.search.SysMenuOperationsSearchCondition;
import com.ce.sys.menu.view.MenuOption;
import com.ce.sys.org.view.OrgTreeNodeProperty;
import com.ce.util.DbUtil;
import com.ce.util.MenuUtil;
import com.ce.util.TreeNode;


/**
* 嫦娥软件有限公司 版权所有 2013
* 创建人：　andy
* 创建日期：2010-10-11
* 创建时间：11:06:39
* 功能描述：菜单表 [SYS_T_MENU]更改时用的Action
* ==============================================
* 修改历史
* 修改人		修改时间		修改原因
*
* ==============================================
*/
public class SysMenuAction extends DataMaintainAction 
{
	private static final long serialVersionUID = 1L;
	private MenuOption opts;

    @Override
	protected void initVcId() throws AppException {
		// TODO Auto-generated method stub
   	 	try {
//			BeanAccessUtil.copyProperty(po, "vcId", GeneratorUUID.generateUUID());
			BeanAccessUtil.copyProperty(po, "vcDelFlag", 0);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
    
    

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		if(StringUtil.isBlank(op)){
			return this.openTreeFrame();
		}
		else{
			if("loadMenu".equals(op)){
				return loadMenu();
			}
		    return super.execute();
		}
	}



	/**
	 * 开发人： andy
	 * 开发时间： 2012-4-18 上午9:59:27
	 * 功能描述：根据指定URL加载菜单数据
	 * 方法的参数和返回值
	 * @return
	 * String 
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	private String loadMenu() {
		String url = getParameter("url");
		List list = null;
		try {
			list = DbUtil.executeHql("from SysTMenuLib po where po.vcUrl='"+url.replace("'", "''")+"' order by po.opSeq");
		} catch (Exception e) {
			LogUtil.logError(e);
		}
		JSONArray ary = new JSONArray();
		ary.addAll(list);
		return writeHTML(ary.toString());
	}



	/**
	 * 开发人： andy
	 * 开发时间： 2013-10-21 下午02:11:58
	 * 功能描述：打开菜单树管理界面
	 * 方法的参数和返回值
	 * @return
	 * String 
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public String openTreeFrame(){
	  	return "menuTreeFrame";
	  }
	
	@Override
	public String look()throws AppException {
    	super.look();
    	String pageUrlStr = "sysMenuManagerViewForRoot";   //页面的返回地址，默认为根节点的查看界面
    	String nodeId = this.getParameter("chkSelf").trim();  //选中的菜单ID
    	if(!"0".equals(nodeId)){
    		//非根节点的转向界面
    		SysMenu menu = (SysMenu)this.baselogic.getPOByPk(SysMenu.class.getName(), nodeId);
    		setAttribute("menu",menu);
    		pageUrlStr = "sysMenuManagerViewPage";
    	}
    	return pageUrlStr;
    }  
    
    @Override
	public String openAddPage() throws AppException {
    	//加载默认操作项目
    	List<?> operateList = this.baselogic.searchByHql("from SysMenuDefaultOperation");
    	setAttribute("defaultOperateList", operateList);
    	List<?> menuLib = DbUtil.executeSqlQuery("select * from (select distinct vc_url,vc_path from sys_t_menu$lib) order by vc_path", TreeNode.mapper2);
    	setAttribute("menuLib", menuLib);
    	int nseq = this.baselogic.getCntByHQL("from SysMenu po where po.vcDelFlag = 0 and po.vcParId = '"+this.getParameter("pid")+"'");
    	setAttribute("nseq", nseq);
		return super.openAddPage();
	}

	@Override
	public String openModifyPage() throws AppException {
		//加载该菜单的所有操作项目
		String menuId = this.getParameter(WebConstants.SELECT_ITEMS_NAME);
		List<?> operateList = this.baselogic.searchByHql("from SysMenuOperations po where po.vcDelFlag = 0 and po.vcMenuId = '"+menuId+"'");
    	setAttribute("operateList", operateList);
		return super.openModifyPage();
	}
    
    /**
     * 开发人： andy
     * 开发时间： 2013-10-11 下午01:07:59
     * 功能描述： 构造JSON的菜单树
     * 方法的参数和返回值
     * @throws AppException
     * void 
     * ==================================
     * 修改历史
     * 修改人        修改时间      修改原因及内容
     *
     * ==================================
     */
    public void searchMenuJsonTree()throws  AppException{
    	List<?> menuList = new ArrayList<Object>();
    	JSONArray jsonTree = new JSONArray();
    	//设置树的根节点的信息
    	JsonTreeNode rootNode = new JsonTreeNode();//根节点
    	String baseSql = "select * from sys_t_menu t ";  //获取机构树的基本sql语句
    	//是超级管理员时加载所有菜单，否则只加载系统管理员菜单
		if(!User.getUser().isSuperUser())
			baseSql = baseSql + " where (t.vc_url is null or t.vc_id in (select t2.vc_menu$id from sys_t_role$permiss t2 where t2.vc_role$id ='admin'))";
		baseSql = baseSql + " start with t.vc_par$id = '0' connect by PRIOR t.vc_id = t.vc_par$id ";
    	//没有上级节点时的处理
    	rootNode.setId("0");
    	rootNode.setText("菜单管理");		
    	StringBuffer sql  = new StringBuffer("select * from ("+baseSql+") where 1=1 and vc_del$flag=0");
    	sql.append(" order by INT_SEQ ASC,VC_NAME Asc");
    	//将通过SQL语句查询的结果集组合成SysVOrg对象的数组
    	menuList = this.baselogic.executeSQLQuery(sql.toString(),new ISQLMapper(){
			public SysMenu fromSQLQuery(ResultSet rs, int row) {
				SysMenu view = new SysMenu();
				try {
					view.setVcId(rs.getString("VC_ID"));
					view.setVcName(rs.getString("VC_NAME"));
					view.setIntLevel(rs.getInt("INT_LEVEL"));
					view.setIntSeq(rs.getInt("INT_SEQ"));
					view.setVcUrl(rs.getString("VC_URL"));
					view.setVcParId(rs.getString("VC_PAR$ID"));
					view.setVcMemo(rs.getString("VC_MEMO"));
					view.setVcIsMerge(rs.getInt("VC_IS$MERGE"));
					view.setVcLinkUrl(rs.getString("VC_LINK$URL"));
					view.setVcIconCls(rs.getString("vc_icon$cls"));
					view.setVcDelFlag(rs.getInt("VC_DEL$FLAG"));		
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return view;
			}
		});

    	List<JsonTreeNode> childList  = this.getChildNodeListForMenu(rootNode.getId(),menuList);  //获取根节点下的全部节点信息
    	rootNode.setChildren(childList); //加载子节点
    	jsonTree.add(rootNode);  //写入树节点信息
    	//以字符串为文件流进行输出
		writeHTML(StringUtil.escapeHTMLTags(jsonTree.toString()));  //将树以JSON格式的字符串进行输出
    }
    
    
    /**
     * 开发人： andy
     * 开发时间： 2013-10-11 下午01:08:18
     * 功能描述：获得子菜单树的JSON格式数据
     * 方法的参数和返回值
     * @param pid
     * @param menuList
     * @return
     * List 
     * ==================================
     * 修改历史
     * 修改人        修改时间      修改原因及内容
     *
     * ==================================
     */
    private List<JsonTreeNode> getChildNodeListForMenu(String pid,List<?> menuList){
    	List<JsonTreeNode> rootList = new ArrayList<JsonTreeNode>();
    	//循环遍历所有机构
    	for(int i=0;i<menuList.size();i++){
    		SysMenu menu = (SysMenu)menuList.get(i);
    		//判断机构信息，当机构的上级ID和参数pid相同时，才将该机构纳入到子节点中
    		if(pid.equals(menu.getVcParId())){
        		JsonTreeNode child = new JsonTreeNode();
            	child.setId(menu.getVcId());
            	child.setText(menu.getVcName());
            	child.setIconCls(menu.getVcIconCls());
                OrgTreeNodeProperty attr = new OrgTreeNodeProperty();
                if(StringUtil.isNotBlank(menu.getVcUrl()))
                    attr.setUrl(menu.getVcUrl());
                attr.setOtherInfo(menu.getVcIsMerge().toString()); //子系统标志位
                child.setAttributes(attr);
            	List<JsonTreeNode> childList = this.getChildNodeListForMenu(menu.getVcId(),menuList);  //递归获取的该节点的下级节点
            	child.setChildren(childList);
            	if(childList!=null&&childList.size()>0)  //当有子节点时默认树的状态为不展开
            	    child.setState("closed");
            	rootList.add(child); //将节点放入List数组中
    		}
    	}
    	return rootList;
    }
    
    protected ISearchCondition creatMainPoCondition() throws AppException {
      // TODO Auto-generated method stub
      return null;
	}
	
    protected ISearchCondition creatChildPoCondition() throws AppException {
    	SysMenuOperationsSearchCondition condition = new SysMenuOperationsSearchCondition();
    	if(getParameter(WebConstants.SELECT_ITEMS_NAME)!=null)
    		condition.setMenuId(getParameter(WebConstants.SELECT_ITEMS_NAME));
        return condition;
    }
    
    protected List<SysMenuOperations> getAddList() throws AppException {
		List<SysMenuOperations> list = null;
		if (opts!=null && opts.getVcName() != null && opts.getVcName().length > 0) {
			list = new ArrayList<SysMenuOperations>();
			for (int i = 0; i < opts.getVcName().length; i++) {
				if (StringUtil.isBlank(opts.getVcId()[i])) { // 获取ID为空的数据（新增）
					SysMenuOperations operate = new SysMenuOperations();
					BeanAccessUtil.copyAryPropts(operate, opts, i);
					operate.setVcId(GeneratorUUID.generateUUID());
					list.add(operate);
				}
			}
		}
		return list;
	}

	protected List<SysMenuOperations> getModifyList() throws AppException {
		List<SysMenuOperations> list = null;
		if (opts!=null && opts.getVcName() != null && opts.getVcName().length > 0) {
			list = new ArrayList<SysMenuOperations>();
			for (int i = 0; i < opts.getVcName().length; i++) {
				if (StringUtil.isNotBlank(opts.getVcId()[i])) { // 获取ID不为空的数据（修改）
					SysMenuOperations operate = (SysMenuOperations) this.baselogic
							.getPOByPk(SysMenuOperations.class.getName(), opts
									.getVcId()[i]);
					if (BeanAccessUtil.copyAryPropts(operate, opts, i))
						list.add(operate);
				}
			}
		}
		return list;
	}
	
	

	@Override
	protected String addItemForJS() {
		// TODO Auto-generated method stub
		try{
			String url = BeanAccessUtil.getFieldValue(po, "vcUrl");
			if(StringUtil.isNotBlank(url)){
				int n = this.baselogic.getCntByHQL("from SysMenu po where po.vcUrl='"+url+"' and po.vcDelFlag = 0");
				if(n>0)
					return super.returnInfoForJS(false, "菜单添加失败，菜单路径已经存在！");	
			}
			super.addItem();
			SysMenu menu = (SysMenu)this.po;
			SysMenu pmenu = (SysMenu)this.baselogic.getPOByPk(SysMenu.class.getName(), menu.getVcParId());
			if(pmenu!=null && pmenu.getIntLevel()==0){
				pmenu.setIntLevel(1); //将上级节点状态设置为非叶子节点
				this.baselogic.updatePo(pmenu);	
			}
			MenuUtil.clearValues();  //清除缓存
		}catch(Exception e){
			LogUtil.logError(e.getMessage());
			return super.returnInfoForJS(false, e.getMessage());
		}

		return super.returnInfoForJS(true, null);
		
	}
	
	

	@Override
	protected String modifyItemForJS() {
		// TODO Auto-generated method stub
		try{
			String url = BeanAccessUtil.getFieldValue(po, "vcUrl");
			String vcId = BeanAccessUtil.getFieldValue(po, "vcId");
			if(StringUtil.isNotBlank(url)){
				int n = this.baselogic.getCntByHQL("from SysMenu po where po.vcUrl='"+url+"' and po.vcDelFlag = 0 and po.vcId!='"+vcId+"'");
				if(n>0)
					return super.returnInfoForJS(false, "菜单修改失败，菜单路径已经存在！");	
			}
			SysMenu menu = (SysMenu)this.po;
			SysMenu pmenu = (SysMenu)this.baselogic.getPOByPk(SysMenu.class.getName(), menu.getVcParId());
			if(pmenu!=null && pmenu.getIntLevel()==0){
				pmenu.setIntLevel(1); //将上级节点状态设置为非叶子节点
				this.baselogic.updatePo(pmenu);	
			}
			super.modifyItem();
			MenuUtil.clearValues();  //清除缓存	
		}catch(Exception e){
			LogUtil.logDebug(e.getMessage());
			return super.returnInfoForJS(false,e.getMessage());
		}
		
		return super.returnInfoForJS(true, null);
	}

	@Override
	protected String delItem() throws AppException {
		// TODO Auto-generated method stub
		super.delItem();
		//删除所选节点的所有子节点
		DbUtil.executeSqlUpdate("update sys_t_menu t  set t.vc_del$flag = 1 where t.vc_id in (select t.vc_id from sys_t_menu t  start with t.vc_par$id = '"+this.getParameter(WebConstants.SELECT_ITEMS_NAME)+"' connect by PRIOR t.vc_id = t.vc_par$id)");
        int cnt = DbUtil.getFirstIntSqlQuery("select count(*) from sys_t_menu t where t.vc_del$flag = 0 and t.vc_par$id = (select m.vc_par$id from sys_t_menu m where m.vc_id='"+this.getParameter(WebConstants.SELECT_ITEMS_NAME)+"')");
		if(cnt==0){
        	//没有子节点即将父节点状态改为子节点
        	DbUtil.executeSqlUpdate("update sys_t_menu t set t.int_level = 0 where t.vc_id = (select m.vc_par$id from sys_t_menu m where m.vc_id='"+this.getParameter(WebConstants.SELECT_ITEMS_NAME)+"')");
        }
		MenuUtil.clearValues();  //清除缓存
		return super.searchData();
	}

	public MenuOption getOpts() {
		return opts;
	}

	public void setOpts(MenuOption opts) {
		this.opts = opts;
	}
}

